import * as THREE from 'three';
import M from 'scripts/main.js';
import { TWEEN } from 'three/addons/libs/tween.module.min.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { CSS3DRenderer, CSS3DObject } from 'three/addons/renderers/CSS3DRenderer.js';
import {Market} from 'scripts/market.js';

class BuyBuilding {
	constructor(param){	

		let animationID, camera_l, scene_l, renderer_l,camera_r, scene_r, renderer_r, container,group;
		let controls;
		const m = new M();

		const objects = [];
		const targets = [];

		init();

		async function init() {
			THREE.Cache.enabled = true;
			m.display("goback",true);
			m.getNode("goback").addEventListener('pointerdown', goback);
			container = m.getNode( 'container' );
			const div_l = m.newNode("div");
			div_l.className="half";
			div_l.style.left="0px";
			container.appendChild(div_l);
			const div_r = m.newNode("div");
			div_r.className="half";
			div_r.style.left="50%";
			container.appendChild(div_r);
			
			window.addEventListener( 'resize', onWindowResize );

			camera_l = new THREE.PerspectiveCamera( 30, (window.innerWidth/2) / window.innerHeight, 1, 1500 );
			camera_l.position.set( 0, 9, 14 );
			camera_l.lookAt( 0, 0, 0 );
			camera_r = new THREE.PerspectiveCamera( 40, (window.innerWidth/2) / window.innerHeight, 1000, 10000 );
			camera_r.position.z = 6000;

			scene_l = new THREE.Scene();
			scene_r = new THREE.Scene();
			
			group = new THREE.Group();
			scene_l.add( group );

			group.add( new THREE.GridHelper( 5, 20, 0x888888, 0x444444 ) );

			const dirLight = new THREE.DirectionalLight( 0x88ffff, 10 );
			dirLight.position.set( 3, 3, 3 );
			group.add( dirLight );
			const dirLight1 = new THREE.DirectionalLight( 0x88ffff, 10 );
			dirLight1.position.set( -3, 3, -3 );
			group.add( dirLight1 );
			//设置模型的载入前位置
			group.position.set( 0, 12, 20 );
			const loader = new GLTFLoader();
			//载入环境
			loader.load( m.current() + "models/"+param.name.substr(2)+'.glb', ( gltf ) => {
				//场景中添加环境
				scene_l.add( gltf.scene );
				gltf.scene.position.set(0,0,0);
				group.add( gltf.scene );							


				renderer_l = new THREE.WebGLRenderer( { antialias: true } );
				renderer_l.setPixelRatio( window.devicePixelRatio );
				renderer_l.setSize( window.innerWidth/2, window.innerHeight );
				div_l.appendChild( renderer_l.domElement );
								
				const controls = new OrbitControls( camera_l, renderer_l.domElement );
				controls.target.set( 0, 1, 0 );
				controls.update();
					
				const info = m.newNode( 'div' );
				info.className = 'card';
				info.style.backgroundColor = 'rgba(0,127,127,0.1)';
				
				const details = m.newNode( 'div' );
				details.className = 'detail';
				details.innerHTML = "名称："+param.name.substr(2)+"<br>"+
					"面积：" + param.name.substr(0,1) + "X" + param.name.substr(1,1)+"<br>"+
					"价格：💰 " + param.price;
				info.appendChild( details );

				const buy = m.newNode( 'div' );
				buy.className = 'buy';
				buy.textContent = '购买';
				info.appendChild( buy );
				buy.addEventListener('pointerdown', function() { 
					let money = parseFloat(m.loadItem("money"));
					let price = param.price;
					if (price > money){
						alert("您的可用金币不足，请从钱包中提现，或去市场购买。");
					}else{
						if (confirm("确定支付"+price+"个金币购买此模型吗？")){
							//TOFO:增加荣誉值
							let nfts = m.loadJson("nfts");
							if (!nfts) nfts=[];
							money -= price; 
							nfts.push({name:param.name.substr(2)});
							m.saveJson("nfts",nfts);
							m.setMoney(money);
							alert("购买成功，模型已放入您的收藏中。");
							goback();
						}
					}
				});

				const object_r = new CSS3DObject( info );
				object_r.position.x = 0;
				object_r.position.y = 0;
				object_r.position.z = 7000;
				scene_r.add( object_r );

				objects.push( group );
				objects.push( object_r );

				const object1 = new THREE.Object3D();
				object1.position.x = 0;
				object1.position.y = 0;
				object1.position.z = 0;

				const object2 = new THREE.Object3D();
				object2.position.x = 0;
				object2.position.y = 0;
				object2.position.z = 5000;

				targets.push( object1 );
				targets.push( object2 );
				
				renderer_r = new CSS3DRenderer();
				renderer_r.setSize( window.innerWidth/2, window.innerHeight );
				div_r.appendChild( renderer_r.domElement );

				transform( targets, 1000 );

				animate();
			} );				
		}
		function goback(){
			destroy();
			new Market();
		}
		function transform( targets, duration ) {

			TWEEN.removeAll();

			for ( let i = 0; i < objects.length; i ++ ) {

				const object = objects[ i ];
				const target = targets[ i ];

				new TWEEN.Tween( object.position )
					.to( { x: target.position.x, y: target.position.y, z: target.position.z }, 2 * duration )
					.easing( TWEEN.Easing.Exponential.InOut )
					.start();

			}

			new TWEEN.Tween( this )
				.to( {}, duration * 2 )
				.onUpdate( render )
				.start();

		}

		function onWindowResize() {

			camera.aspect = window.innerWidth / window.innerHeight;
			camera.updateProjectionMatrix();

			renderer.setSize( window.innerWidth, window.innerHeight );

			render();

		}

		function animate() {

			animationID = requestAnimationFrame( animate );
			group.rotation.y = performance.now() / 3000;
			TWEEN.update();

			render();

		}

		function render() {

			renderer_l.render( scene_l, camera_l );
			renderer_r.render( scene_r, camera_r );

		}

		function destroy(){
			cancelAnimationFrame(animationID)
			TWEEN.removeAll();
			scene_l.clear();
			scene_r.clear();
			renderer_l.content = null;
			renderer_r.content = null;

			m.getNode("goback").removeEventListener('pointerdown', goback);
			window.removeEventListener( 'resize', onWindowResize );
			container.children[0].removeChild(renderer_l.domElement);
			container.children[1].removeChild(renderer_r.domElement);
			container.removeChild(container.children[1]);
			container.removeChild(container.children[0]);
			scene_l = null;
			scene_r = null;
			camera_l = null;
			camera_r = null;
			controls = null;
			renderer_l = null;
			renderer_r = null;
		}			
	}
}
export { BuyBuilding };